package com.alipay.app.groupmeal.standard.ui.c.abcp;

import static com.alipay.app.groupmeal.standard.constant.ConfigConstant.onOffLine;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.KeyEvent;

import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;
import com.alipay.app.groupmeal.standard.bean.AliPayResVo;
import com.alipay.app.groupmeal.standard.constant.ConfigConstant;
import com.alipay.app.groupmeal.standard.event.EventManager;
import com.alipay.app.groupmeal.standard.http.bean.resp.Result;
import com.alipay.app.groupmeal.standard.offline.bean.FkBean;
import com.alipay.app.groupmeal.standard.offline.bean.OrderBean;
import com.alipay.app.groupmeal.standard.offline.manager.FkBeanManager;
import com.alipay.app.groupmeal.standard.offline.manager.OrderDataManager;
import com.alipay.app.groupmeal.standard.ui.b.PayingPre;

import com.alipay.app.groupmeal.standard.ui.b.util.WIth;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.payment.PaymentAPI;
import com.alipay.sdk.abcphaima.AbcpHM;
import com.alipay.sdk.abcphaima.AbcpHMFree;
import com.alipay.sdk.abcphaima.bean.PageResultData;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;

/**
 * 支付中
 */
public class CPayingAbcpActivity extends BaseMVCActivity {

    private PayingPre payingPre;

    private String amount;

    public static final String AMOUNT = "amount";
    private int payType = 0;
    private String order = "";

    public static CPayingAbcpActivity payingActivity = null;


    public static void startActForAbcp(Activity activity, String amount) {
        //自我启动，带上金额
        Intent intent = new Intent(activity, CPayingAbcpActivity.class);
        intent.putExtra(AMOUNT, amount);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_transparent;
    }

    @Override
    protected void initView() {
        payingActivity = this;
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        amount = intent.getStringExtra(AMOUNT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        payingActivity = null;

    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            //副屏显示
            payingPre = new PayingPre(this, mDisplay);
            registerPresentation(payingPre);
            showPresentation(payingPre);
            //显示支付中金额
            payingPre.showWaitPay(amount);
        }
        abcp();
    }

    @Override
    protected void dissmissPresnetation() {
        if (payingPre != null) {
            payingPre.dismiss();
        }
    }

    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        finish();
        return super.onKeyEventBack(event);
    }

    private String mSessionId;
    private String mTradeNo;

    private void abcp() {
        //显示支付中金额
        //自由金额模式
        //自由拍照付
        AbcpHMFree.startFreeFace(amount, ConfigConstant.expireTime, new AbcpHM.AbcpScanFaceCallback() {
            @Override
            public void onSuccess(boolean isFace, String authCode, String barCode, String tradeNo, String sessionId, String alipayUid) {
                payingPre.showPaying(amount);
                mSessionId = sessionId;
                mTradeNo = tradeNo;
                if (isFace) {
                    //刷脸返回
                    facePay(isFace, authCode, alipayUid);
                } else {
                    //扫码返回值
//                    if ("1".equals(authCode.substring(0, 1))) {
//                        payType = 1;
//                    } else {
//                        payType = 0;
//                    }
//                    qrPay(isFace, authCode, alipayUid);
//                    payingPre.showQrCheck();
                }
            }

            @Override
            public void onFail(String code, String msg) {
                System.out.println("失败操作");
                EventBus.getDefault().post(new EventManager.clearAmount());
                //刷脸失败
                finish();
            }

            @Override
            public void onEvent(String sessionId) {
                mSessionId = sessionId;
                System.out.println("获取sessionId" + sessionId);
                Flowable.intervalRange(0, 5, 0, 1, TimeUnit.SECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnNext(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                String btnText = (5 - aLong) + "秒";
                                System.out.println("到时：" + btnText);
                            }
                        })
                        .doOnComplete(new Action() {
                            @Override
                            public void run() throws Exception {
//                                finish();
                                AbcpHMFree.closeFreeFace(sessionId);
                            }
                        })
                        .subscribe();

            }
        });
    }

    private void facePay(boolean isFace, String faceToken, String aliUid) {
        PaymentAPI api = APIManager.getInstance().getPaymentAPI();
        String terminal_params = api.signWithDelegated(faceToken);
        if (!onOffLine) {
            //脱机交易模式
            FkBean fkBean = FkBeanManager.getInstance().getFkByAliUserId(aliUid);
            if (fkBean == null) {
                toResult(isFace ? 0 : 1, faceToken, amount,
                        mTradeNo, mSessionId, "", false,
                        0, "1", "查无此人");
                return;

            } else if (new BigDecimal(amount).compareTo(new BigDecimal(fkBean.getKye())) == -1) {
                OrderBean orderBean = new OrderBean();
                orderBean.setSuccess(true);//在线模式，订单为未知状态，则不是成功状态
                orderBean.setHavePost(false);//在线模式，订单服务器上操作，则表示为上传订单
                orderBean.setAmount(amount);
                orderBean.setAuthCode(faceToken);
                orderBean.setTradeNo(mTradeNo);
                orderBean.setCreateTime(new Date());
                orderBean.setCardno(fkBean.getCardno());
                orderBean.setUserName(fkBean.getName());
                orderBean.setTerminalParams(terminal_params);
                OrderDataManager.getInstance().insert(orderBean);
                toResult(isFace ? 0 : 1, faceToken, amount,
                        mTradeNo, mSessionId, "", true,
                        0, "1", "支付成功");
                System.out.println("isFace：支付成功");
            } else {
                toResult(isFace ? 0 : 1, faceToken, amount,
                        mTradeNo, mSessionId, "", false,
                        0, "1", "余额不足");
            }
            return;
        }

        OrderBean orderBean = new OrderBean();
        orderBean.setSuccess(false);//在线模式，订单为未知状态，则不是成功状态
        orderBean.setHavePost(true);//在线模式，订单服务器上操作，则表示为上传订单
        orderBean.setAmount(amount);
        orderBean.setAuthCode(faceToken);
        orderBean.setTradeNo(mTradeNo);
        orderBean.setCreateTime(new Date());
        OrderDataManager.getInstance().insert(orderBean);

        new WIth(this).facePay(amount,
                mTradeNo,
                mSessionId,
                faceToken,
                aliUid, terminal_params,
                new BlockingBaseObserver<Result<AliPayResVo>>() {
                    @Override
                    public void onNext(@NonNull Result<AliPayResVo> aliPayResVoResult) {
                        AliPayResVo aliPayResVo = aliPayResVoResult.getResult();
                        toResult(isFace ? 0 : 1, faceToken, amount,
                                mTradeNo, mSessionId, "", aliPayResVo.isSuccess(),
                                aliPayResVo.getIsFailType(), aliPayResVo.getFailCode(), aliPayResVo.getMsg());
                        if (aliPayResVo.isSuccess()) {
                            //支付成功订单，需要更改标志，并存入数据库
                            orderBean.setCardno(aliPayResVo.getFk().getCardno());
                            orderBean.setUserName(aliPayResVo.getFk().getName());
                            orderBean.setSuccess(true);
                            OrderDataManager.getInstance().update(orderBean);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }
                });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //TODO  todo somthing here
                System.out.println("延时启动");
                wxCheckOrderHandler();
            }
        }, 10 * 1000);  //延迟10秒执行
    }


    /**
     * 微信查单任务·
     */
    private void wxCheckOrderHandler() {
        EventBus.getDefault().post(new EventManager.clearAmount());
        finish();
    }


//    private void qrPay(boolean isFace, String faceToken, String aliUid) {
//        PaymentAPI api = APIManager.getInstance().getPaymentAPI();
//        String terminal_params = api.signWithDelegated(faceToken);
//        OrderBean orderBean = new OrderBean();
//        orderBean.setSuccess(false);//在线模式，订单为未知状态，则不是成功状态
//        orderBean.setHavePost(true);//在线模式，订单服务器上操作，则表示为上传订单
//        orderBean.setAmount(amount);
//        orderBean.setAuthCode(faceToken);
//        orderBean.setTradeNo(mTradeNo);
//        orderBean.setCreateTime(new Date());
//        OrderDataManager.getInstance().insert(orderBean);
//        new WIth(this).facePay(amount,
//                mTradeNo,
//                mSessionId,
//                faceToken,
//                aliUid, terminal_params,
//                new BlockingBaseObserver<Result<AliPayResVo>>() {
//                    @Override
//                    public void onNext(@NonNull Result<AliPayResVo> aliPayResVoResult) {
//                        if (payType == 1 && aliPayResVoResult.getResult().isSuccess()) {
//                            order = aliPayResVoResult.getResult().getMsg();
//                            //启动线程查单操作
//
//
//                            return;
//                        }
//                        AliPayResVo aliPayResVo = aliPayResVoResult.getResult();
//                        toResult(isFace ? 0 : 1, faceToken, amount,
//                                mTradeNo, mSessionId, "", aliPayResVo.isSuccess(),
//                                aliPayResVo.getIsFailType(), aliPayResVo.getFailCode(), aliPayResVo.getMsg());
//                        if (aliPayResVo.isSuccess()) {
//                            //支付成功订单，需要更改标志，并存入数据库
//                            orderBean.setCardno(aliPayResVo.getFk().getCardno());
//                            orderBean.setUserName(aliPayResVo.getFk().getName());
//                            orderBean.setSuccess(true);
//                            OrderDataManager.getInstance().update(orderBean);
//                        }
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable e) {
//
//                    }
//                });
//    }


    private void toResult(int type, final String authCode, String amount,
                          final String tradeNo, final String sessionId, String buyerLogonId,
                          boolean isSuccess, int isFailType, String failCode, String msg) {
        PageResultData pageResultData = new PageResultData();
        pageResultData.success = isSuccess;
        if (isSuccess) {
            pageResultData.buyerLogonId = buyerLogonId;
        } else {
            pageResultData.failCode = failCode;
            pageResultData.message = msg;
        }
        pageResultData.totalAmount = amount;
        pageResultData.paidAmount = amount;
        pageResultData.authCode = authCode;
        pageResultData.tradeNo = tradeNo;
        pageResultData.sessionId = sessionId;
        pageResultData.type = type;
        CPayResultAbcpActivity.startAct(CPayingAbcpActivity.this, pageResultData);
    }

    @Override
    public void onEvent(Object event) {
        super.onEvent(event);
        //查单操作


    }
}
